<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Notebook;
use Dingo\Api\Http\Request;

class NotebookController extends BaseController
{

    public $model = Notebook::class;

    public function store(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'cookbook_id' => 'required|exists:cookbooks,id',
            'message' => 'required',
            'file_path' => 'required'
        ]);
        $input['user_id'] = $this->getUserId();
        $info = $this->model::create($input);
        $id = $info->id;
        return $this->success($id);
    }


    public function index(Request $request) {
        $this->validate($request, [
            'type' => 'required|in:somebody,focus,all,cookbook,detail',
        ]);
        $user = $this->getUser();
        $input = $request->input();
        $model = new Notebook();

        if ($input['type'] == 'focus') {
            $target_user_ids = $user->focus()->pluck('target_user_id')->all();
            array_push($target_user_ids, $user->id);
            $model = $model->whereIn('user_id', $target_user_ids);
        } else if($input['type'] == 'somebody') {
            $this->validate($request, [
                'target_user_id' => 'required',
            ]);
            $target_user_ids = [$input['target_user_id']];
            $model = $model->whereIn('user_id', $target_user_ids);
        } else if($input['type'] == 'cookbook') {
            $this->validate($request, [
                'cookbook_id' => 'required',
            ]);
            $cookbook_id = $request->input('cookbook_id');
            $model = $model->cookBookId($cookbook_id);
        } else if($input['type'] == 'detail') {
            $this->validate($request, [
                'id' => 'required',
            ]);
            $id = $request->input('id');
            $model = $model->where('id', $id);
        }

        $list = $model->withCertain('cookbook', ['title'])
            ->withCertain('user', ['nickname', 'avatar_url'])
            ->userFocus($user->id)
            ->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

}

